<template>
    <div class="body">
        <!--搜索栏-->
        <div class="empSearch">
            <el-form :inline="true" :model="employees" class="demo-form-inline" :rules="rules" ref="ruleForm">
                <el-form-item label="姓名" prop="name">
                    <el-input size="mini" v-model="employees.name" placeholder="姓名"></el-input>
                </el-form-item>
                <el-form-item label="编号" prop="no">
                    <el-input  size="mini" v-model.number="employees.no" placeholder="编号"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select size="mini"  v-model="employees.sex">
                        <el-option label="全部" value=""></el-option>
                        <el-option v-for="(sex,index) in sexArray" :key="sex.id" :label="sex.name" :value="sex.value"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item  label="员工类型" >
                    <el-select  size="mini"  v-model="employees.types" multiple placeholder="全部">
                        <el-option
                                v-for="item in optionsType"
                                :key="item.id"
                                :label="item.name"
                                :value="item">
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item prop="date">
                    <el-date-picker
                            size="mini"
                            v-model="date"
                            type="datetimerange"
                            align="left"
                            format="yyyy-MM-dd HH:mm:ss"
                            value-format="yyyy-MM-dd HH:mm:ss"
                            range-separator="至"
                            start-placeholder="开始日期"
                            end-placeholder="结束日期">
                    </el-date-picker>
                </el-form-item>

                <el-form-item>
                    <el-button icon="el-icon-search" size="small " type="primary" @click="onSubmit('ruleForm')">查询</el-button>
                    <el-button icon="el-icon-plus" size="small " type="primary" @click="showInsertPage=!showInsertPage">新增</el-button>
                    <el-button icon="el-icon-edit" size="small" type="warning" @click="updateEmp">编辑</el-button>
                    <el-button icon="el-icon-delete" size="small" type="danger" @click="deleteEmp">删除</el-button>
                    <el-popover style="margin-right: 10px"
                            placement="top"
                            width="200"
                            trigger="click">
                        <div>
                            <el-upload
                                    class="upload-demo"
                                    multiple
                                    action=""
                                    :before-upload="beforeUpload"
                                    :on-exceed="handleExceed"
                                    :http-request="uploadFile"
                                    accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                                    :limit="1">
                                <el-button type="success" size="small" ><i class="el-icon-upload el-icon--right"></i>选择文件</el-button>
                                <div slot="tip" class="el-upload__tip">只能上传excel文件,限制大小10M</div>
                            </el-upload>
                        </div>
                        <div style="margin-top: 10px">
                            <el-button type="primary" size="small" @click.prevent="templateDownload">
                                <i class="el-icon-download el-icon--right"></i>
                                下载模版
                            </el-button>
                        </div>
                        <el-button type="primary" size="small"  slot="reference" style="margin-left: 10px" ><i class="el-icon-upload el-icon--right"></i>上传</el-button>
                    </el-popover>
                    <el-button type="primary" size="small" @click.stop.prevent="employeeExport">
                        <i class="el-icon-download el-icon--right"></i>
                        导出
                        <span @click.stop="">
                            <el-switch
                                    style="height: 10px"
                                    v-model="employees.switchValue"
                                    active-color="#13ce66"
                                    inactive-color="#201a13">
                            </el-switch>
                            <el-tooltip content="默认导出当前页面检索内容,勾选后导出所有检索内容" :style="{ fontSize: '12px',marginLeft:'5px' }" placement="top">
                                <i class="el-icon-question"></i>
                            </el-tooltip>
                        </span>
                    </el-button>
                </el-form-item>
            </el-form>
        </div>
        <!--弹窗新增页面-->
        <insert v-if="showInsertPage"></insert>
        <!--弹窗修改页面-->
        <update :emp="multipleSelection[0]" v-if="showUpdatePage"></update>
        <div class="empTable" style="width: 100%;">
            <el-table
                    ref="multipleTable"
                    :data="tableDataView"
                    :highlight-current-row="true"
                    @cell-click="rowClick"
                    row-key="id"
                    :expand-row-keys="expandedKeys"
                    max-height="450"
                    @selection-change="handleSelectionChange"
            style="width: 99%">
                <el-table-column
                        type="index"
                        width="55">
                </el-table-column>
                <el-table-column
                        type="selection"
                        width="55">
                </el-table-column>
                <el-table-column type="expand">
                    <template slot-scope="props">
                        <el-form  label-position="left" inline class="demo-table-expand">
                            <el-form-item  label="姓名">
                                <span>{{ props.row.name }}</span>
                            </el-form-item>
                            <el-form-item label="编号">
                                <span>{{ props.row.no }}</span>
                            </el-form-item>
                            <el-form-item label="性别">
                                <span>{{ props.row.sex }}</span>
                            </el-form-item>
                            <el-form-item label="年龄">
                                <span>{{ props.row.age }}</span>
                            </el-form-item>
                            <el-form-item label="手机">
                                <span>{{ props.row.phone }}</span>
                            </el-form-item>
                            <el-form-item label="邮箱">
                                <span>{{ props.row.email }}</span>
                            </el-form-item>
                            <el-form-item label="类型">
                                <span v-for="(p,index) in props.row.types" :key="p.id">
                                    {{ p.name }}
                                    <span v-if="index !== props.row.types.length - 1">,</span>
                                </span>
                            </el-form-item>
                            <el-form-item label="创建时间">
                                <span>{{ props.row.createTime}}</span>
                            </el-form-item>
                        </el-form>
                    </template>
                </el-table-column>
                <el-table-column
                        label="姓名"
                        prop="name">
                </el-table-column>
                <el-table-column
                        label="编号"
                        prop="no">
                </el-table-column>
                <el-table-column
                        label="创建时间"
                        prop="createTime">
                </el-table-column>
            </el-table>
        </div>
        <div class="empLimitPage">
            <el-pagination
                    background
                    @size-change="handleSizeChange"
                    @current-change="currentChange"
                    layout="sizes, prev, pager, next , total"
                    :page-sizes="[10, 20, 100]"
                    :page-size="10"
                    :total="totalCount">
            </el-pagination>
        </div>
    </div>
</template>

<script>
    import Big from 'big.js';
    import Insert from "./Insert";
    import {EmployeeList} from "@/utils/api";
    import Update from "./Update";
    import {EmployeeDelete, EmployeeExport, EmployeeImport, EmployeeTemplateDownload,DictionaryList} from "../../utils/api";

    export default {
        name: "Employees",
        components: {Update, Insert},
        data(){
            return{
                expandedKeys: [],
                multipleSelection:[],
                optionsType: [],
                sexArray:[],
                employees:{
                        name:'',
                        no:'',
                        sex: '',
                        types:[],
                        createTime:'',
                        endTime:'',
                        switchValue: false,
                        current:1,
                        size:10
                },
                tableData: [],
                tableDataView:[],
                showInsertPage:false,
                showUpdatePage:false,
                rules:{},
                totalCount:100,
                date:[]
            }
        },
        computed:{
        },
        methods:{
            onSubmit(formName){
                this.$refs[formName].validate((valid) => {
                    if (valid) {
                        this.selectEmpList(this.employees);
                    } else {
                        console.log('error submit!!');
                        return false;
                    }
                });
            },
            handleExceed(){
                this.$message.warning("只能上传一个文件");
            },
            beforeUpload(file){
                if(file.size > 1024*1024*10){
                    this.$message.error("文件大小不能大于10m");
                    return false;
                }
              if(file.name.endsWith(".xls") || file.name.endsWith(".xlsx")){
                  return true;
              }else{
                  this.$message.error("文件类型错误")
                  return false;
              }
            },
            uploadFile(param){
                console.log(param.file)
                let formData = new FormData()
                formData.append("file",param.file)
                EmployeeImport(formData).then((response)=>{
                    this.$message.success("上传"+param.file.name+"成功")
                    this.selectEmpList(this.employees);
                })
            },
            selectEmpList(params){
                EmployeeList(params)
                    .then(response => {
                        this.tableData=response.data.records;
                        this.totalCount=response.data.total;
                        this.tableDataView = JSON.parse(JSON.stringify(this.tableData));
                        //性别转换
                        for (let i = 0; i < this.tableDataView.length; i++) {
                            let match = this.sexArray.find(item => item.value == this.tableDataView[i].sex);
                            if (match) {
                                this.tableDataView[i].sex = match.name;
                            }
                        }
                    })

            },
            rowClick(row, column, cell, event){
                const key = row.id;
                const index = this.expandedKeys.indexOf(key);
                if (index === -1) {
                    // 当前行未展开，进行展开,且只显示当前行
                    this.expandedKeys=[];
                    this.expandedKeys.push(key);
                    this.$refs.multipleTable.clearSelection();
                    this.$refs.multipleTable.toggleRowSelection(row,true);

                    const  index = this.tableDataView.indexOf(row) ;
                    this.multipleSelection[0] = this.tableData[index];
                } else {
                    // 当前行已展开，进行折叠
                    this.expandedKeys.splice(index, 1);
                    this.$refs.multipleTable.toggleRowSelection(row,false);
                }

            },
            handleSelectionChange(selection){
                this.multipleSelection=selection;

            },
            updateEmp(){
                if(this.multipleSelection.length>1){
                    this.$message.error("只能选择一条记录")
                }else if(this.multipleSelection.length==1){
                    this.showUpdatePage=!this.showUpdatePage;
                }else{
                    this.$message.error("请选择一条记录")
                }
            },
            deleteEmp(){
                if(this.multipleSelection.length>0){
                    const names = this.multipleSelection.map(item => item.name);

                    this.$confirm('是否删除?\xa0\xa0\xa0\xa0'+names, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        const ids = this.multipleSelection.map(item => item.id);

                // const queryParams = new URLSearchParams(params).toString(); params请求方式转换

                        EmployeeDelete(ids).then((response)=>{
                            this.$message({
                                type: 'success',
                                message: '删除成功!'
                            });
                            this.selectEmpList(this.employees)
                        })
                    }).catch(() => {
                        this.$message({
                            type: 'info',
                            message: '已取消删除'
                        })
                    });

                }else{
                    this.$message.error("请选择一条记录")
                }
            },
            templateDownload(){
                EmployeeTemplateDownload({name:'要一个文件'}).then((response)=>{
                    let blobURL=URL.createObjectURL(response.data);
                    let link = document.createElement("a");
                    link.href=blobURL;
                    link.download='员工登记信息模板.xlsx';

                    link.style.display='none';
                    link.click();
                    URL.revokeObjectURL(blobURL);
                    this.$message.success("下载模版成功")
                })
            },
            employeeExport(){
                EmployeeExport(this.employees).then((response)=>{
                    let blobURL=URL.createObjectURL(response.data);
                    let link = document.createElement("a");
                    link.href=blobURL;
                    link.download='员工登记信息.xlsx';
                    link.style.display='none';
                    link.click();
                    URL.revokeObjectURL(blobURL);
                    this.$message.success("导出员工成功")
                })
            },
            currentChange(currentPage){
                this.employees.current=currentPage;
                this.selectEmpList(this.employees);
            },
            handleSizeChange(size){
                this.employees.size=size;
                this.selectEmpList(this.employees);
            },
        },
         created() {
             DictionaryList("code=Employee").then(response => {
                 this.optionsType=response.data.records;
             })
             DictionaryList("code=Sex").then(response => {
                 this.sexArray=response.data.records;
             })

            this.$bus.$on('showInsertPage',(value)=>{
                this.showInsertPage=value;
                this.selectEmpList(this.employees);
            });

             this.$bus.$on('showUpdatePage',(value)=>{
                 this.showUpdatePage=value;
                 this.selectEmpList(this.employees);
             });

             this.selectEmpList(this.employees);

        },
        watch: {
            date(newDate) {
                this.employees.createTime = newDate[0];
                this.employees.endTime = newDate[1];
            }
        },
    }
</script>

<style scoped>
    .el-form-item{
        margin-left: 20px;
    }

    .demo-table-expand {
        font-size: 0;
    }
    .demo-table-expand label {
        width: 90px;
        color: #99a9bf;
    }
    .demo-table-expand .el-form-item {
        margin-right: 0;
        margin-bottom: 0;
        width: 50%;
    }

</style>